import Dep from "./Dep";
var uid = 0
export default class Watcher{
    constructor(target,expression,callback) {
        this.id = uid ++
        this.target  = target
        this.expression = expression
        this.callback = callback
        this.getter = parsePath(expression)
        this.value = this.get()

    }
    get(){
        Dep.target = this
        const obj = this.target
        var value
        try{
            value = this.getter(obj)
        }finally {
            Dep.target = null
        }
        return value
    }
    update(){
        //唤起
        this.run()
    }
    run(){
        //处理回调函数
        this.getAndInvoke(this.callback)
    }
    getAndInvoke(cb){
        const newValue = this.get()
        if(newValue !== this.value || typeof value == 'object'){
            const oldValue = this.value
            this.value = newValue
            cb.call(this.target,newValue,oldValue)
        }
    }


}
//高阶函数
function parsePath(str){
    const segment = str.split('.')
    return obj =>{
        for(let i = 0,l = segment.length;i<l;i++){
            if(!obj) return
            obj = obj[segment[i]]
        }
        return obj
    }
}